//
//  MusicHallBLL.m
//  LZMusicPlayer
//
//  Created by wulanzhou on 2016/11/7.
//  Copyright © 2016年 wulanzhou. All rights reserved.
//

#import "MusicHallBLL.h"
#import "CacheDataUtil.h"
#import "BMABillboard.h"
#import "BMAGeDan.h"

#define kCacheNewestListKey @"kCacheNewestListKey"
#define kCacheHotGeDanListKey @"kCacheHotGeDanListKey"

@interface MusicHallBLL () {
    NSArray<NewestBillboard *> *_newestList;
    NSArray<HotGeDan *> *_hotList;
    
    void (^MusicHallDataCompletion) ();
}

@end


@implementation MusicHallBLL

@synthesize newestSongList=_newestList;
@synthesize hotGeDanList=_hotList;

- (NSArray<NewestBillboard *> *)newestSongList{
    
    if (!_newestList) {
        NSArray *arr=[CacheDataUtil unarchiveValueForKey:kCacheNewestListKey];
        if (arr&&[arr count]>0) {
            _newestList=arr;
        }
    }
    return _newestList;
}

- (NSArray<HotGeDan *> *)hotGeDanList{
    if (!_hotList) {
        NSArray *arr=[CacheDataUtil unarchiveValueForKey:kCacheHotGeDanListKey];
        if (arr&&[arr count]>0) {
            _hotList=arr;
        }
    }
    return _hotList;
}

- (void)loadCompletion: (void (^) ())completion{
    MusicHallDataCompletion = completion;
}


- (void)getDataBack
{
    dispatch_group_t group = dispatch_group_create();
    
    dispatch_group_enter(group);
    
    BMABillboard *request=[[BMABillboard alloc] init];
    __weak BMABillboard *_WSELF=request;
    [request setCZRequestURL:^NSString *{
        return [_WSELF newestBillSongList];
    }];
    
    [request starWithFinishedBlock:^(NSError *error, id result) {
        if (!error) {
            _newestList = [NewestBillboard mj_objectArrayWithKeyValuesArray:result[@"song_list"]];
            [CacheDataUtil setValueArchiver:_newestList forKey:kCacheNewestListKey];
            dispatch_group_leave(group);
        }
    }];
    
    dispatch_group_enter(group);
    
    BMAGeDan *geDanRequest=[[BMAGeDan alloc] init];
    __weak BMAGeDan *_WSGeELF=geDanRequest;
    [geDanRequest setCZRequestURL:^NSString *{
        return [_WSGeELF hotGeDan:6];
    }];
    
    [geDanRequest starWithFinishedBlock:^(NSError *error, id result) {
        if (!error) {
            
            _hotList = [HotGeDan mj_objectArrayWithKeyValuesArray:[result[@"content"] objectForKey:@"list"]];
            [CacheDataUtil setValueArchiver:_hotList forKey:kCacheHotGeDanListKey];
            dispatch_group_leave(group);
        }
    }];

    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        //[self.tableView reloadData];
        
        NSLog(@"finished!!!");
        if (MusicHallDataCompletion) {
            MusicHallDataCompletion();
        }
    });
}

@end
